package com.java110.mall.user.cmd.register;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.*;
import com.java110.dto.privilege.PrivilegeUserDto;
import com.java110.dto.store.StoreDto;
import com.java110.dto.user.StoreStaffDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.user.IPrivilegeUserV1InnerServiceSMO;
import com.java110.intf.user.IStoreStaffV1InnerServiceSMO;
import com.java110.intf.user.IStoreV1InnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.privilege.PrivilegeUserPo;
import com.java110.po.store.StorePo;
import com.java110.po.user.StoreStaffPo;
import com.java110.po.user.UserPo;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.vo.ResultVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.net.URLDecoder;

/**
 * 用户注册 功能
 * 请求地址为/app/register.pcUserRegister
 */

@Java110Cmd(serviceCode = "register.pcUserRegister")
public class PcUserRegisterCmd extends Cmd {
    private final static Logger logger = LoggerFactory.getLogger(PcUserRegisterCmd.class);
//    @Autowired
//    private IUserLoginInnerServiceSMO userLoginInnerServiceSMOImpl;

    public static final String CODE_PREFIX_ID = "10";

    @Autowired
    private IStoreV1InnerServiceSMO storeV1InnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMO;

    @Autowired
    private IStoreStaffV1InnerServiceSMO storeStaffV1InnerServiceSMOImpl;

    @Autowired
    private IPrivilegeUserV1InnerServiceSMO privilegeUserV1InnerServiceSMOImpl;

    public static final String TEST_SMSCODE = "1111";

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) {
        //getJSONObject(cmdDataFlowContext.getReqData(), reqJson);

        Assert.hasKeyAndValue(reqJson, "username", "用户注册，未包含username节点，请检查");
        Assert.hasKeyAndValue(reqJson, "password", "用户登录，未包含password节点，请检查");
        Assert.hasKeyAndValue(reqJson, "repassword", "用户登录，未包含repassword节点，请检查");
        Assert.hasKeyAndValue(reqJson, "tel", "用户登录，未包含tel节点，请检查");
        Assert.hasKeyAndValue(reqJson, "messageCode", "用户注册，未包含验证码，请检查");
        Assert.hasKeyAndValue(reqJson, "levelCd", "用户注册，未包含用户类型，请检查");

        String code = CommonCache.getValue(reqJson.getString("tel") + "_validateTel");
        ResponseEntity<String> verifyResult = null;
        if (!reqJson.getString("messageCode").toLowerCase().equals(code)) {
            throw new CmdException("验证码错误");
        }
        validateUsernameAndTel(reqJson);
        validatePassword(reqJson);
        reqJson.put("username", URLDecoder.decode(reqJson.get("username").toString()));
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

        UserPo userPo = new UserPo();
        userPo.setUserId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_userId));
        userPo.setName(reqJson.get("username").toString());
        userPo.setPassword(AuthenticationFactory.passwdMd5(reqJson.get("password").toString()));
        userPo.setTel(reqJson.get("tel").toString());
        userPo.setLevelCd(reqJson.get("levelCd").toString());
        userPo.setCreateUser(userPo.getName());
        userPo.setAccountStatus(UserPo.ACCOUNT_STATUS_NORMAL);
        int flag = userV1InnerServiceSMO.saveUser(userPo);
        if (flag < 1) {
            throw new CmdException("注册失败");
        }

        cmdDataFlowContext.setResponseEntity(ResultVo.success());
    }


    private void validateUsernameAndTel(JSONObject reqJson) {
        UserDto userDto = new UserDto();
        userDto.setName(reqJson.get("username").toString());
        int count = userV1InnerServiceSMO.queryUsersCount(userDto);
        if (count > 0) {
            throw new CmdException("用户名已存在");
        } else {
            userDto.setName("");
            userDto.setTel(reqJson.get("tel").toString());
            count = userV1InnerServiceSMO.queryUsersCount(userDto);
            if (count > 0) {
                throw new CmdException("手机号已存在");
            }
        }
    }

    private void validatePassword(JSONObject reqJson) {
        String password = reqJson.get("password").toString();
        String repassword = reqJson.get("repassword").toString();
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(repassword) || !password.equals(repassword)) {
            throw new CmdException("请检查两次密码输入是否一致");
        }
    }
}
